import { login , getUserInfo , getUserDetailById } from '@/api/user'
import { getToken , setToken, removeToken , setTimeStamp , getTimeStamp } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {},
  }
}

const state = getDefaultState()

const mutations = {
  // set token
  setToken (state,data) {
    state.token = data;
    setToken(data)
  },
  // remove token
  removeToken (state) {
    state.token = null;
    removeToken()
  },
  // get user info
  setUserInfo (state, userInfo) {
    state.userInfo = {...userInfo}
  },
  // remove userInfo
  removeUserInfo (state) {
    state.userInfo = {};
  }
}

const actions = {
  // user login
  async login({commit}, data) {
    const results = await login(data)
    commit("setToken", results)
    // 设置时间戳
    setTimeStamp()
  },
  

  // get user info
  
  async getUserInfo ( {commit} ) {
    const res = await getUserInfo();
    const baseInfo = await getUserDetailById(res.userId)
    const baseResult = {...res,...baseInfo}
    commit("setUserInfo" , baseResult)
    return res
  },

  // user logout
  loginout ( {commit} ) {
    commit("removeToken");
    commit("removeUserInfo");
    resetRouter();
    commit('permission/setRoutes',[],{root: true})
  }

  // remove token
}


export default {
  namespaced: true,
  state,
  mutations,
  actions
}

